<!--新建大屏-->
<template>
  <el-drawer
    size="700px"
    title="新建大屏活动"
    :visible="visible"
    @close="updateVisible(false)">
    <el-form
      :rules="rules"
      label-position="left"
      label-width="110px"
      class="e-padding"
      :show-message="false"
      :hide-required-asterisk="false"
      ref="form"
      :model="form"
      @keyup.enter.native="submit"
      @submit.native.prevent
    >
      <el-form-item label="大屏名称" class="set-class check-star"  prop="largeScreenName">
        <el-input class="m-top10" v-model="form.largeScreenName" placeholder="请输入大屏名称"/>
      </el-form-item>


      <el-form-item label="背景图" class="flex-columns check-star set-class"
                    prop="backgroundImage">
        <div class="flex-between upload-class">
          <div class="font-overflow">建议上传1920px * 1080px尺寸</div>
        </div>
        <ele-image-upload
          accept=".jpg,.jpeg,.png"
          :limit="1"
          :multiple="false"
          v-model="fileList"
          :auto-upload="false"
          :before-remove="onBeforeRemove"
        />
       <!-- <el-upload
          accept=".jpg,.jpeg,.png"
          :on-change="onUpload"
          class="avatar-uploader flex"
          :action="ossUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <div v-else class="avatar-uploader-icon flex-column">
            <i class="el-icon-picture"></i>
            <div>上传背景</div>
          </div>
        </el-upload>-->
      </el-form-item>

      <el-form-item label="发布渠道" class="set-class check-star">
        <div class="flex-align-center width100 p-top10">
          <div v-for="(i,j) in typeList" :key="j" :class="(Number(form.releaseChannel)-1) == j ? 'sel-title-class' : 'title-class'" class="pointer" @click="typeClick(j)">
            {{i.name}}
          </div>
        </div>
      </el-form-item>

      <el-form-item label="发布设置" prop="shareToPublish" class="set-class check-star" v-if="form.releaseChannel==1">
        <!--<el-radio-group v-model="form.shareToPublish" class="width100 p-top10">
          <el-radio :label="1">跳转到发布页（减少用户操作）</el-radio>
          <el-radio :label="0">跳转到剪辑页</el-radio>
        </el-radio-group>
        -->
        <div class="flex-align-center width100 p-top10">
          <div v-for="(i,j) in publishList" :key="j" :class="form.shareToPublish == j ? 'sel-title-class' : 'title-class'" class="pointer" @click="publishClick(j)">
            {{i.name}}
          </div>
        </div>
      </el-form-item>

      <el-form-item label="选择视频素材" class="set-class check-star">
        <div class="flex-columns width100">
          <div class="flex-align-center p-algin10">
            <div v-for="(i,j) in materialType" :key="j" :class="(Number(form.materialType)-1) == j ? 'sel-title-class' : 'title-class'" class="pointer" @click="materialTypeClick(j)">
              {{i.name}}
            </div>
          </div>

          <!--关联活动-->
          <div class="flex-columns width100" v-if="form.materialType==1">
           <!-- <div class="flex-align-center" style="margin:8px 8px 20px">
              <el-radio-group v-model="form.montageType" @input="projectInit">
                <el-radio :label="2">口播剪辑</el-radio>
                <el-radio :label="1">AI剪辑</el-radio>
                <el-radio :label="3">图文剪辑</el-radio>
              </el-radio-group>
            </div>-->
            <!--关联活动-->
            <activities ref="connected" :dataInfo="form" @getData="getData" :hint="hint"></activities>
          </div>
          <div class="flex-columns width100" v-else>
            <!--关联活动-->
            <piecesCom ref="connected" :dataInfo="form" @getData="getData" :hint="hint"></piecesCom>
          </div>

          <!--<el-select
            v-else
            v-model="form.material"
            placeholder="请选择文件夹"
            class="ele-block"
            clearable
            @change="selectMaterial"
          >
            <el-option :label="i.name" :value="i" v-for="(i,j) in cameraList" :key="j" />
          </el-select>-->
        </div>
      </el-form-item>
      <!--剪辑数量-->
     <!-- <el-form-item label="剪辑数量" prop="editingNumber" class="set-class check-star" v-if="form.materialType==1"
                    :class="!form.editingNumber && hint ?'select-cls':''">
        <div class="flex-align-center delInput width100">
          <el-input
            class="in-append"
            type="number"
            :min="1"
            @input="maxClick"
            v-model.number="form.editingNumber"
            placeholder="请输入剪辑数量"
            clearable>
          </el-input>
        </div>
      </el-form-item>-->

      <el-form-item label="SEO文案" class="set-class check-star"
                    :class="!form.seoCopywriting && hint ?'select-cls':''">
        <!--SEO文案-->
        <div class="width100">
          <acties ref="seoActies" :lists="seoList" @getData="selectCopy"></acties>
        </div>
      </el-form-item>

      <el-form-item label="赞助商" class="set-class">
        <div class="flex-align-center width100 p-top10">
          <div v-for="(i,j) in form.sponsors" :key="j" v-if="form.sponsors.length>0" class="flex-align-center">
            <img :src="i.prizePicture" style="margin-right: 10px;height: 40px" />
            <!--<i class="el-icon-remove-outline"></i>-->
          </div>
          <i class="el-icon-circle-plus-outline icon-class pointer" @click="sponsorClick"></i>
          <new-sponsor ref="new" :visible.sync="newShow" @getSponsors="getSponsors"></new-sponsor>
        </div>
      </el-form-item>


      <el-form-item label="大屏规则" class="set-class check-star">
        <el-col style="padding: 0 10px" class="m-top10">
          <!--v-if防止tinymce在弹框创建前创建-->
          <tinymce-editor
            v-if="visible"
            ref="editor"
            v-model="form.largeScreenRules"
            :init="option"
            :disabled="false"
          />
        </el-col>
      </el-form-item>
    </el-form>
    <div class="flex-end m-bottom20">
      <el-button round @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" class="margin20" round  @click="confirm()" :loading="loading">保存</el-button>
    </div>

  </el-drawer>
</template>

<script>
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  import acties from "@/components/pagination/activities";
  import piecesCom from '@/components/activities/pieces-activities'
  import activities from '@/components/activities/connected-activities'
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  import {addLargeScreen} from "@/api/explosiveCode/largeScreenLottery";
  import NewSponsor from "@/views/explosiveCode/largeScreenLottery/components/new-sponsor";
  import {userOssSignature} from "@/api/creatCenter/material";
  import {getToken} from "@/utils/token-util";
  import axios from "axios";
  import {querySeo} from "@/api/matrixManage/seo";
  import {submitDiyJob, submitImageJob, submitProjectJob} from "@/api/explosiveCode/releaseActivity";
  export default {
    name: "new-screen",
    components: {NewSponsor, TinymceEditor,activities,EleImageUpload,acties,piecesCom},
    props: {
      visible:Boolean
    },
    data(){
      const defaultForm = {
        merchantId: this.$store.state.user.info.merchantId,  // 商户id
        shareToPublish:0,
        largeScreenName:'', // 大屏名称
        releaseChannel:1,
        materialType:1,
        backgroundImage:'',  // 背景图
        sponsors:[], // 赞助商
        largeScreenRules:'', // 大屏规则
      }
      return{
        // 云闪推成片库列表
        cameraList:[],
        defaultForm,
        // 上传背景图片url
        fileList:[{
          url:'https://z4a.net/images/2023/08/18/Group-263950b924336c666948.png'
        }],
        imageUrl:'',
        rules: {
          largeScreenName: [
            {
              required: true,
              message: '请输入大屏名称',
              trigger: 'blur'
            }
          ],
        },

        // seo 列表
        seoList:[],
        seoInfo:{
          username:this.$store.state.user.info.username,
          limit:10,
          page:1,
          // seo 所属平台：1D音2K手3视频号
          platform:1
        },
        newShow:false, // 赞助商弹框
        montageIndex:0,
        loading:false,
        hint:'',
        form:{ ...defaultForm},
        publishList:[
          {
            name:'跳转到剪辑页'
          },
          {
            name:'跳转到发布页（减少用户操作）'
          }
        ],
        typeList: [
          {
            name:'D音',
            id:1
          },
          {
            name:'K手',
            id:2
          }
        ],
        materialType: [
          {
            name:'云创作成片库',
            id:1
          },
          {
            name:'云闪推成片库',
            id:2
          }
        ],

        activityType: [
          {
            name:'口播剪辑',
            id:2
          },
          {
            name:'AI剪辑',
            id:1
          },
          {
            name:'图文剪辑',
            id:3
          }
        ],
        maxNum:0,
        sponsorList:[], // 赞助商列表
        option: {
          height: 520,
          // 自定义文件上传(这里使用把选择的文件转成 blob 演示)
          file_picker_callback: (callback, _value, meta) => {
            const input = document.createElement('input');
            input.setAttribute('type', 'file');
            // 设定文件可选类型
            if (meta.filetype === 'image') {
              input.setAttribute('accept', 'image/*');
            } else if (meta.filetype === 'media') {
              input.setAttribute('accept', 'video/*');
            }
            input.onchange = () => {
              const file = input.files?.[0];
              if (!file) {
                return;
              }
              if (meta.filetype === 'media') {
                if (!file.type.startsWith('video/')) {
                  this.$refs.editor.alert({ content: '只能选择视频文件' });
                  return;
                }
              }
              if (file.size / 1024 / 1024 > 20) {
                this.$refs.editor.alert({ content: '大小不能超过 20MB' });
                return;
              }
              const reader = new FileReader();
              reader.onload = (e) => {
                if (e.target?.result != null) {
                  const blob = new Blob([e.target.result], { type: file.type });
                  callback(URL.createObjectURL(blob));
                }
              };
              reader.readAsArrayBuffer(file);
            };
            input.click();
          }
        },
      }
    },
    methods:{

      // “剪辑数量”输入事件 （修改）
      /*maxClick(e){
        console.log(' “剪辑数量”输入事件',e)
        if(this.maxNum>0 && this.maxNum<e){
          this.form.editingNumber = this.maxNum
        }
      },*/

      show(){
        this.$nextTick(() => {
          this.$refs['connected'].init()
        })
        this.seoInit()
        this.fileList=[{
          url:'https://z4a.net/images/2023/08/18/Group-263950b924336c666948.png'
        }]
      },

      // 获取“seo文案”
      selectCopy(e){
        console.log('选择文案',e)
        this.form.seoCopywritingId=e.id //SEO ID
        this.$set(this.form,'seoCopywriting',e.taticsName)  //SEO名称
        // this.form.seoCopywriting=e.taticsName //SEO名称
        console.log('this.form=======',this.form)
      },

      seoInit(){
        if(this.form.seoCopywriting){
          delete this.form.seoCopywritingId
          this.$set(this.form,'seoCopywriting','')  //SEO名称
          delete this.form.seoCopywriting
          this.$refs['seoActies'].clear()
        }
        this.querySeoList()
      },
      querySeoList(){
        // 查询SEO文案【分页查询】 在查询列表页使用
        querySeo(this.seoInfo)
          .then((data) => {
            console.log('seoInit==========data.',data,'this.$refs[\'seoActies\']',this.$refs['seoActies'])
            this.seoList=data.list
            this.$nextTick(()=>{
              this.$refs['seoActies'].init()
            })
          })
          .catch((e) => {
            console.log("进入catch111111======",e)
            this.$message.error(e.msg);
          });
      },

      getData(e){
        this.form.shopCodeId=e?e.id:'' //剪辑工程ID
        // this.maxNum=e.max
        // 剩余剪辑数量
        // this.maxNum=e.max-e.montageCount
        // this.maxNum=e.max    展示剩余剪辑数量隐藏
        // 修改用于填写“剪辑数量”
        /*if(this.form.editingNumber){
          this.maxClick(this.form.editingNumber)
        }*/
        console.log("this.form=============",this.form,'e',e)
      },

      projectInit(e){
        // this.montageIndex=e
        if(this.form.shopCodeId){
          delete this.form.shopCodeId     //剪辑工程ID
        }
        this.$nextTick(() => {
          this.$refs['connected'].init()
        })
      },



      /* 删除增加确认弹窗 */
      onBeforeRemove() {
        return new Promise((resolve, reject) => {
          this.$confirm('确定要删除吗?', '提示', {
            type: 'warning'
          })
            .then(() => {
              resolve();
            })
            .catch(() => {
              reject();
            });
        });
      },

      /* 上传 暂未使用start*/
      onUpload(file) {
        this.fileList=[]
        this.fileList.push(file)
        console.log('this.fileList',this.fileList)
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isJPG = file.type;
        const isLt4M = file.size / 1024 / 1024 < 4;

        const extension1 = file.type === "image/jpg";
        const extension2 = file.type === "image/jpeg";
        const extension3 = file.type === "image/png";
        if (!extension1 && !extension2 && !extension3) {
          this.$message.error("请上传jpg 、png、jpeg 类型图片!");
        }
        if (!isLt4M) {
          this.$message.error('上传图片大小不能超过 4MB!');
        }
        return isJPG && isLt4M;
      },
      /* 上传 暂未使用end*/



      // 切换 “发布设置”
      publishClick(e){
        this.form.shareToPublish=e;
      },
      // 切换 ‘类型’
      typeClick(e){
        // 发布渠道 1_抖音 2_快手
        this.form.releaseChannel=this.typeList[e].id
        // seo 所属平台：1D音2K手3视频号
        this.seoInfo.platform=this.form.releaseChannel  // 需修改（seo所属平台id 和channelList，id 对应不上
        this.seoInit()
      },
      // 切换 ‘类型’
      materialTypeClick(e){
        // 素材类型 1.云创作成片库 2.云闪推成片库
        this.form.materialType=this.materialType[e].id
        this.form.shopCodeId=''
      },
      // 赞助商 点击事件
      sponsorClick(){
        this.newShow=true
      },
      // 选择素材
      selectMaterial(e){
        console.log('e',e)
      },
      // 获取赞助商数组
      getSponsors(e){
        console.log('获取赞助商数组sponsors=',e,e.length)
        this.form.sponsors=e
      },
      confirm(){
        console.log("this.rules222",this.rules,'this.fileList ',this.fileList )
        this.$refs.form.validate((valid, obj) => {
          console.log('valid',valid,'obj',obj)
          for(let i in obj){
            console.log("i",i)
            console.log("obj=========",obj[i][0].message)
            this.hint=obj[i][0].message
            break
          }
          console.log('this.hint',this.hint)
          if (valid) {

            // if(!this.imageUrl){
            if(this.fileList.length<=0){
              this.$message.error("请上传背景图")
              return
            }
            // materialType：1_云创作成片库 2_摄像头任务
            if(!this.form.shopCodeId && this.form.materialType==1 || !this.form.shopCodeId && this.form.materialType==2){
              this.$message.error("请选择视频素材")
              return
            }
            /*if(!this.form.editingNumber && this.form.materialType==1){
              this.$message.error('请输入剪辑数量')
              return
            }
            if(this.form.editingNumber <= 0 && this.form.materialType==1 || this.form.editingNumber =='e' && this.form.materialType==1){
              this.$message.error('请输入有效的剪辑数量')
              return
            }*/
            // materialType：1_云创作成片库 2_摄像头任务
            if(!this.form.seoCopywriting){
              this.$message.error("请选择文案")
              return
            }
            if(!this.form.largeScreenRules){
              this.$message.error("请输入大屏规则")
              return
            }
            // 只有抖音才有发布设置
            if(this.form.releaseChannel!=1){
              delete this.form.shareToPublish
            }
            this.loading=true
            console.log("this.fileList[0]",this.fileList[0],'this.fileList[0].url',this.fileList[0].url)
            // 默认背景图存在则进入
            if(this.fileList[0].url=='https://z4a.net/images/2023/08/18/Group-263950b924336c666948.png'){
              this.form.backgroundImage=this.fileList[0].url;
              this.save()
            }
            else{
              this.uploadBj()  // 上传背景图
            }
          } else {
            console.log("进入非空提示",valid,'22',this.form)
            this.$message.error(this.hint)
            return false;
          }
        });
      },

      async uploadBj(){
        if(this.fileList.length < 1) {
          this.$message.error('请选择文件后提交');
        }
        // 获取文件上传签名数据
        this.data = await userOssSignature()
        for(let i=0;i<this.fileList.length;i++){
          let file = this.fileList[i].file
          // let file = this.fileList[i].raw
          let filename=file.name;
          let markIndex=(filename).lastIndexOf('.');
          let suffix=filename.substring(markIndex)    // 图片后缀(例.jpg)
          let date=new Date().getTime();    // 当前时间戳
          // 构建请求参数
          let param = new FormData()
          param.append("key", this.data.dir + date+suffix)
          param.append("policy", this.data.policy)
          param.append("OSSAccessKeyId", this.data.accessId)
          param.append("success_action_status", '200')
          // param.append("callback",  this.data.callback)     //回调（not)
          param.append("signature", this.data.signature)
          param.append("file", file, file.name)
          param.append('success_action_status', '200')
          let config = {
            headers: {
              'Access-Control-Allow-Origin': '*',
              'x-oss-callback-Authorization': getToken()
            }
          }
          axios.post(this.data.host, param, config).then(res => {
            if(res.status==200){
              console.log('this.data.host',this.data.host+'/'+date+suffix)
              let url=this.data.host+'/'+date+suffix;
              this.form.backgroundImage=url;
              this.save()
            }
            else{
              this.loading=false
              this.$message.error('上传失败');
            }

          }).catch(err => {
            console.log(err)
          })
        }
      },
      save(){

        this.form.username=this.$store.state.user.info.username
        // 新建大屏
        addLargeScreen(this.form)
          .then((data) => {
            this.loading=false
            this.$emit('reload')
            this.$message.success('新增成功!');
            this.updateVisible(false)
            console.log("确定提交22222222222",data,'this.form======',this.form)
            // this.submitTo()
          })
          .catch((e) => {
            this.loading=false
            this.$message.error(e);
          });
      },
      //  提交
      submitTo(){
        // <!-- * 1脚本剪辑 =AI剪辑 * 2自定义剪辑=口播剪辑 * 3图文剪辑-->
        const typeApi = this.form.montageType ==1 ? submitProjectJob : this.form.montageType ==2 ? submitDiyJob : submitImageJob
        typeApi({
          id: this.form.shopCodeId,//剪辑工程主键ID
          maximumCount:this.form.editingNumber, //剪辑工程所属用户
          username:this.$store.state.user.info.username
        })
          .then((data) => {
            this.loading=false
            this.$emit('reload')
            this.$message.success('新增成功!');
            this.updateVisible(false)
            console.log("确定提交22222222222",data,'this.form======',this.form)
          })
          .catch((e) => {
            this.updateVisible(false)
            this.$message.error(e);
          });
      },
      /* 更新 visible */
      updateVisible(value) {
        if(value==false){
          this.form.materialType=1
          this.seoInfo.platform=1
          this.seoInit()
          this.form = { ...this.defaultForm }
          if(this.fileList.length>0 && this.fileList[0].url!='https://z4a.net/images/2023/08/18/Group-263950b924336c666948.png'){
            this.fileList=[]
            this.imageUrl=''
          }
        }
        this.$emit('update:visible', value);
      },
    }
  }
</script>

<style scoped>
  /*隐藏input（type=number)右边的小箭头*/
  /deep/.delInput input::-webkit-outer-spin-button,
  /deep/.delInput input::-webkit-inner-spin-button {
    -webkit-appearance: none!important;
  }
  /deep/.delInput input[type="number"]{
    -moz-appearance: textfield;
  }

  .e-padding{
    padding: 20px 15px;
  }
  .title-class,.sel-title-class{
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 21px;
    min-width: 100px;
    padding: 0 15px;
    height: 35px;
    border-radius: 5px;
  }
  .title-class{
    color: #757575;
    background: #FAFAFC;
  }
  .sel-title-class{
    color: #1E6CEB;
    background: #DDF0FF;
  }
  .m-left40{
    margin-left: 40px
  }
  /*赞助商class start*/
  .icon-class{
    /*margin-left: 20px;*/
    font-size: 40px;
    color: #1890ff;
  }
  /*end*/

  /*上传背景start*/
  .avatar-uploader{
    margin: 0;
    padding: 0;
    outline: none;

    /* 修改 start*/
    border: 1px solid #D9D9D9;
    border-radius: 2px;
    /*end*/
    width: 88px;
    height: 88px;
  }
  /*  ‘背景图’上传 start */
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    color: #D9D9D9;
    text-align: center;
  i{
    font-size: 28px;
  }
  div{
    padding-top: 3px;
  }
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
  /*  end*/
</style>
